﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using wjy自制小框架.Common;
using wjy自制小框架.Common.Pojo;
using wjy自制小框架.Web;

namespace wjy自制小框架
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();

            // 设置路径，打包时使用
            //webView.Source = new Uri(Application.StartupPath + "/public/index.html");
        }

        /// <summary>
        /// 取消右键功能，打包时使用
        /// </summary>
        //private void webView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        //{
        //    webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(
        //        "document.addEventListener('contextmenu', function(e) { e.preventDefault(); });");
        //}

        /// <summary>
        /// html与主机通信
        /// </summary>
        private void webView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            Func<Task> action = async () =>
            {
                await Task.Delay(10);
                AjaxResult response;
                try
                {
                    var param = JObject.Parse(e.WebMessageAsJson);
                    var url = param.Value<string>("url");
                    var data = param.Value<JObject>("data");
                    response = new CommonController().Start(url, data);
                }
                catch (Exception ex)
                {
                    response = AjaxResult.error();
                    response.data = ex.Message;
                }
                webView.CoreWebView2.PostWebMessageAsJson(JsonConvert.SerializeObject(response));
            };

            action();
        }
    }
}
